angular.module('starter.controllers', [])

//首页
.controller('MainCtrl', function($scope,$state,$rootScope,$timeout) {
	$scope.Track_Matte = false;
    $scope.selectedIndex = 1;
	//退出应用
    $scope.gohomeFun = function (){
	    closeWebView("",function (){
	        console.log('应用退出成功！');
	    },function (){
	        console.log('应用退出失败！');
	    });
    }
    //侧边栏切换
    if('pad' == platform){
        $state.go('menu.list.user_details',{'id':''});
        $scope.clickMain = function (type,padurl,phoneurl){
            $scope.selectedIndex = type;
            $state.go(padurl,{'id':''});
            $scope.Track_Matte = false;
            $scope.selectedRow = 'a';
        }
    }else{
        $scope.clickMain = function (type,padurl,phoneurl){
            $scope.selectedIndex = type;
            $state.go(phoneurl,{'id':''});
        }
    }
    $timeout(function(){  
        //强制横屏
        setScreenLandscape("",function(success){ 
        },function(faild){ 
        });
    },1000); 
})

//菜单
.controller('UserListCtrl', function($scope,$state,$ionicPopup,$timeout,$rootScope,$compile,$ionicActionSheet,FormObj) {
	//loading
     successPopup = $ionicPopup.show({
          content:'loading...'
     });
    //用户列表
    $timeout(function(){ 
    	MenuList($scope,$compile,$ionicPopup,$timeout);
    },1000)
    //关闭、后退一步
	$scope.closeTheCurrent = function(){
		$scope.Track_Matte = false;
		$rootScope.$viewHistory.backView.go();
	}
    //彻底关闭
    $scope.backToStart = function(){
       $scope.Track_Matte = false;
       $scope.selectedRow = '-1';
       $state.go('menu.list.user_details',{'id':''});
    }
	//保存基本信息
    $scope.SubmitFun = function (SelectdCollection){
        //alert("");
        // 全部验证
        var returnFalg = '';
        
        //保存
        //if(SelectdCollection.REAL_NAME == undefined || SelectdCollection.SEX == undefined || SelectdCollection.REAL_NAME == ''){
        
        if(submitVerification($scope,SelectdCollection,returnFalg)){
       		if(SelectdCollection.SEX == undefined){
        		
        		document.getElementById("sex_error").style.display='block';
        		var alertPopup2 = $ionicPopup.alert({
                   template: '<div class="pop_up_box">请选择性别！</div>'
                });
		            $timeout(function() {
		                alertPopup2.close();
		            }, 3000);
        	}else{
        		InsertDatabase($scope,SelectdCollection,$state,$compile,$rootScope,$ionicPopup,$timeout);
            	//清空表单
        		EmptyForm($scope,SelectdCollection)
        	}
        }else{
        	
             var alertPopup = $ionicPopup.alert({
                   template: '<div class="pop_up_box">请完善信息！</div>'
                });
            $timeout(function() {
                alertPopup.close();
            }, 3000);
        }
    }
	//删除用户
    $scope.deleteUser = function(ID){
        $ionicActionSheet.show({
            destructiveText: '删除',
            cancelText: '取消',
            cancel: function() {
            },
            destructiveButtonClicked: function(){
                DeleteForm($state,$compile,ID,$scope,$ionicPopup,$timeout); 
                return true;
            }
        });
    }
    //跳转路径
    if('pad' == platform){
        //点击菜单
        $scope.clickMenu = function (ID,i){
            $scope.selectedRow = i;
            $scope.cancle_but = true;
            $state.go('menu.list.user_details',{'id':ID});  
        }
        //新建
        $scope.NewUserFun = function(){
            $scope.selectedRow = '-1';
            $scope.cancle_but = true;
            $scope.Track_Matte = true;
            $state.go('menu.list.compile_user',{'id':''});
        }
        //编辑
        $scope.CompileUserFun = function(ID){
            $scope.Track_Matte = true;
            $scope.cancle_but = true;
            $state.go('menu.list.compile_user',{'id':ID});
        }
    }else{
    	//点击菜单
        $scope.clickMenu = function (ID,i){
            $scope.selectedRow = i;
            $scope.cancle_but = false;
            $state.go('user_details',{'id':ID});
        }
        //编辑
        $scope.CompileUserFun = function(ID){
            $scope.cancle_but = false;
            $state.go('compile_user',{'id':ID});
        }
    	//新建
    	$scope.NewUserFun = function(){
            $state.go('compile_user',{'id':''});
        }
    }
})

//客户详情
.controller('UserDetailsCtrl', function($scope,$stateParams,$ionicActionSheet,$compile,$state,DetailsTabs,labels,$ionicPopup) {  
    $scope.labels = labels;
	//创建建议书、被保人、投保人
    if(recommend == 1){
    	$scope.chooseInsurance = "选为投保人";
    }else if(recommend == 2){
    	$scope.chooseInsurance = "选为被保人";
    }else{
    	$scope.chooseInsurance = "创建建议书";
    }
    //跳转应用
    $scope.JumpApp = function(){
    	if(recommend == 1 ||recommend == 2){
            var key ={};
            key["recommend"] = recommend;
            var array ={};
            array["id"] = $scope.SelectdCollection.ID,//客户编号
            array["name"] = $scope.SelectdCollection.REAL_NAME,//客户姓名
            array["birth"] = $scope.SelectdCollection.BIRTHDAY,//客户生日
            array["age"] = "",//客户年龄
            array["sex"] = $scope.SelectdCollection.SEX,//客户性别
            array["ocup_code"] = $scope.SelectdCollection.OCCUPATION_CODE,//职业代码
            array["ocup_name"] = "",//职业名称
            array["ocup_type"] = "",//职业类型
            array["part_code"] = $scope.SelectdCollection.PLURALITY_OCCUPATION_CODE,//兼职代码
            array["part_name"] = "",//兼职名称
            array["part_type"] = "" //兼职类型
            key["info"] = array;
            closeWebView(key,function (){
                console.log('客户选择成功！');
            },function (){
                console.log('客户选择失败！');
            });
        }else{
           jumpToOtherApp($scope);
        }
    }
    //客户信息
    if($stateParams.id){ 
        $scope.cancle_but = true;
        QueryCustomerDetails($scope,$stateParams.id)  
        
    }else{
        $scope.cancle_but = false;
    }
    //更多操作
    $scope.MoreActionsFun = function(){
        if($scope.more_actions == undefined || $scope.more_actions == false){
            $scope.more_actions = true;
        }else{
            $scope.more_actions = false;
        }
        if( $scope.more_actions == true){
            $scope.HideFun = function(){
                $scope.more_actions = false;
            }
        }
    }
    //创建建议书
    $scope.createRecommend = function (){
        jumpToOtherApp();
    }
    //tab
    $scope.tabs = DetailsTabs;
    tabSwitch($scope);

})

//编辑客户 ---- 新建客户
.controller('CompileUserCtrl',function($state,$scope,$stateParams,$compile,$ionicPopup,$timeout,FormObj,tabs,information,labels,$ionicModal,occupationQuery){
    
    /**清空表单数据 徐彬 2014-11-26**/
    FormObj = new Object();
    /******************************/
    $scope.labels = labels;
    $scope.OCCUPATION = occupationQuery;

    //表单验证
    formValidation($scope);
//    //js清空新建的输入框
//    $timeout(function(){
//        $('#name_input').val('');
//        $('#clear_address').val('');
//        $('#accout_clear').val('');
//        $('#clear_identify').val('');
//        $('#clear_come').val('');
//        $('#clear_work').val('');
//        $('#clear_height').val('');
//        $('#weight_clear').val('');
//        $('#habit_clear').val('');
//    },500);
    //职业代码查询
    // Form data for the login modal
      $scope.loginData = {};

      $ionicModal.fromTemplateUrl('templates/occupation_query.html', {
        scope: $scope
      }).then(function(modal) {
        $scope.modal = modal;
      });

      // Triggered in the login modal to close it
      $scope.closeLogin = function() {
        $scope.modal.hide();
      };

      

      // Open the login modal
      $scope.login = function() {
        $scope.modal.show();
      };

      // Perform the login action when the user submits the login form
      $scope.searchQuery = function() {
            if($scope.OCCUPATION.WORD == 'undefined' || $scope.OCCUPATION.WORD == '' ){
                alert("请输入职业名称/职业代码");
            }else{
                queryList("query_items",$scope,$compile);
                setTimeout(function(){
                    $("#query_items .table_items").on('click',function(){
                        $scope.modal.hide();
                        document.getElementById('input_proname').value=$(this).attr("code_name");
                        document.getElementById('input_procode').value=$(this).attr("code");
                    })
                },1000);              
            }
        }
    $scope.F_info = true;
	//tabs
    $scope.tabs = tabs;
    tabSwitch($scope);
    //表单 下拉选择项
    $scope.information = information;
    //新建、编辑
	if($stateParams.id){
		//客户信息
		QueryCustomerDetails($scope,$stateParams.id);
		
	}else{
		
		$scope.SelectdCollection = FormObj;
		/**禁止编辑姓名 徐彬 2014-11-26********************************/
		$('#name_input').attr("disabled", "disabled");
		$('#name_input').css({ 'border-color': '#CCCCCC' });
		/*********************************************************/
	}
    //出生年月
    $scope.birthoayDate = function(){
        datePicker('getDate',function(date){
            var birth_date = date.year+'-'+date.month+'-'+date.dayOfMonth;
            $scope.BIRTHDAY = birth_date;
            $('.birthoayDate').text(birth_date);
            /**计算年龄**/
            var myDate = new Date();
            var month = myDate.getMonth() + 1;
            var day = myDate.getDate();
            var age = myDate.getFullYear() - birth_date.substring(0, 4) - 1;
            if ((birth_date.substring(4, 6) < month || birth_date.substring(4, 6) == month) && birth_date.substring(6, 8) <= day) { 
                age++;
            }
            $('.birthoayDate + span').text(age+'岁');

        },function(){
            alert("日期失败")
        });
    }
    //身份证的有效期
    if($scope.ID_END_DATE == '长期有效'){
        $scope.ClassName = 1;
	}
    $scope.validityDate = function(){
         datePicker('getDate',function(date){
            $scope.ID_END_DATE = date.year+'-'+date.month+'-'+date.dayOfMonth;
            $('.validityDate').text(date.year+'-'+date.month+'-'+date.dayOfMonth);
            $scope.ClassName = '2';
        },function(){
            alert("日期失败")
        });
    }
    //长期有效
    $scope.longTerm = function(){
        if( $scope.ClassName == 1 ){
            $scope.isEffective = '请选择身份证有效期';
            $('.validityDate').text('请选择身份证有效期');
            $scope.ClassName = '';
        }else{
            $scope.isEffective = true;
            $('.validityDate').text('长期有效');
            $scope.ClassName = 1;
        }

    }
    //特殊纪念日
    $scope.specialDay = function(){
    	datePicker('getDate',function(date){
			$scope.ANNIVERSARY = date.year+'-'+date.month+'-'+date.dayOfMonth;
			$('.specialDay').text(date.year+'-'+date.month+'-'+date.dayOfMonth);
		},function(){
			alert("日期失败")
		});
    }
    //添加家属 --- 显示、隐藏按钮
    $scope.AddFamiliesFun = function(){
        $scope.AddFamilies = true;
    }
    $scope.CancelAddFun = function(){
        $scope.AddFamilies = false;
    }
    //选择日期
    $scope.FamiliesDate = function(){
	    datePicker('getDate',function(date){
			var FamiliesDate= date.year+'-'+date.month+'-'+date.dayOfMonth;
	    	/**计算年龄**/
			var myDate = new Date(); 
			var month = myDate.getMonth() + 1; 
			var day = myDate.getDate(); 
			var age = myDate.getFullYear() - FamiliesDate.substring(0, 4) - 1; 
			if ((FamiliesDate.substring(4, 6) < month || FamiliesDate.substring(4, 6) == month) && FamiliesDate.substring(6, 8) <= day) { 
				age++; 
			}
	    	$('.FamiliesDate p').text(date.year+'-'+date.month+'-'+date.dayOfMonth)
			$('.FamiliesDate span').text(age);  
		},function(){
			alert("日期失败")
		});
        
    }
	//添加家属
	$scope.SaveFamiliesFun = function(SelectdCollection){
		CreateFamilyInformation($scope,$compile,SelectdCollection,$stateParams.id,$ionicPopup,$timeout);
		var familyInfo ="";
        if(SelectdCollection.F_SEX == '1'){
            SelectdCollection.F_SEX = '女';
        }else if(SelectdCollection.F_SEX == '0'){
            SelectdCollection.F_SEX ='男';
        }else{
            SelectdCollection.F_SEX = '';
        }
		familyInfo += '<div class="user_info">' +
	                 '<h4 class="del-families">' +
	                     SelectdCollection.RELATION +
	                     '<span class="delete_node"></span>' +
	                     '<span></span>' +
	                 '</h4>' +
	                 '<p>' +
	                     '<span>姓名:</span>' +
	                     SelectdCollection.FamiliesName +
	                 '</p>' +
	                 '<p>' +
	                     '<span>性别:</span>' +
	                     SelectdCollection.F_SEX+
	                 '</p>' +
	                 '<p>' +
	                     '<span>出生日期:</span>' +
	                     $('.FamiliesDate p').text() +
	                 '</p>' +
	                 '<p>' +
	                     '<span>年龄:</span>' +
	                     $('.FamiliesDate span').text() + '岁' +
	                 '</p>' +
	             '</div>';
		var i = $compile(familyInfo)($scope);
		var left_btn = document.getElementById('family_info'); 
		angular.element(left_btn).append(i);
		//清空表单
		$('.FamiliesDate p').text("出生日期");
		$('.FamiliesDate span').text("年龄");
		var array =["SelectdCollection.RELATION","SelectdCollection.FamiliesName","SelectdCollection.sex"];
		plugs.clearFormValSet($scope,array);
		$scope.AddFamilies = false;	
    } 
})

/***********************************************客户标签***************************************************************/

//标签
.controller('LabelListCtrl',function($scope,$state,$timeout,$compile){ 

    //加载标签列表
    $timeout(function(){
       labelList("labellist",$scope,$compile);
        $scope.Track_Matte = false;
        $scope.cancle_but = false; 
    },500); 

    if('pad' == platform){
        $state.go('menu.label.label_details',{'id':'','name':''});
    };

    //添加标签
    if ('pad' == platform) {    
        $scope.AddNewLabelFun = function(){
            $scope.Track_Matte = true;
            $scope.cancle_but = true;
            $state.go('menu.label.new_label');
        }       
    }else{
        $scope.AddNewLabelFun = function(){
            $scope.cancle_but = true;
            $state.go('new_label');
        } 
    };

    //点击查看标签下得客户
    if ('pad' == platform) {
       $scope.clickList = function (itemId,name){
            $scope.selectedRow = itemId;
            $scope.Track_Matte = true;
            $scope.cancle_but = true;
            $state.go('menu.label.label_details',{'id':itemId,'name':name});
        }   
    }else{
       $scope.clickList = function (itemId,name){ 
           $scope.selectedRow = itemId;
           $scope.cancle_but = true;
           $state.go('label_details',{'id':itemId,'name':name});    
       } 
    };
    
})

//标签详情列表
.controller('LabelDetailsCtrl',function($scope,$state,$stateParams,$rootScope,$compile,customerMark){ 

    if($stateParams.id){//编辑客户标签
        $scope.title = $stateParams.name;
        $scope.cMark = customerMark;
        $scope.cMark.NAME = $stateParams.name;
        $scope.cMark.ID = $stateParams.id;
        $scope.cancle_but = true;

        if ('pad' == platform) {
            $scope.LabelSuccessFun = function(){
                
                changeLabel($scope,$compile);
                $scope.Track_Matte = false;
                $scope.cancle_but = false; 
                $state.go('menu.label.label_details',{'id':'','name':''});    
            }
        }else{
            $scope.LabelSuccessFun = function(){
                changeLabel($scope,$compile);
                $scope.cancle_but = false; 
                $state.go('label_list',{'id':""});    
            } 
        };
    }else{//添加客户标签
        $scope.cMark = customerMark;
        $scope.cMark.NAME = "";
        $scope.cMark.ID = plugs.getUUid();
        $scope.cancle_but = false;

        if ('pad' == platform) {
            $scope.LabelSuccessFun = function(){
                addLabel($scope,$compile);
                $scope.Track_Matte = false;
                $scope.cancle_but = false; 
                $state.go('menu.label.label_details',{'id':'','name':''});    
            }
        }else{
            $scope.LabelSuccessFun = function(){
                addLabel($scope,$compile);
                $scope.cancle_but = false; 
                $state.go('label_list',{'id':""});    
            } 
        };
    } 

    //关闭/取消
    $scope.CloseFun = function(){
        $scope.Track_Matte = false;
        $scope.cMark.NAME = "";
        $rootScope.$viewHistory.backView.go();
    }

    //编辑标签
    if ('pad' == platform) {
        $scope.rewriteFun = function(){
            $scope.Track_Matte = true;
            $scope.cancle_but = true;
            $state.go('menu.label.rewrite_label',{'id':$stateParams.id,'name':$stateParams.name}); 
        }   
    }else{
        $scope.rewriteFun = function(){
            $scope.Track_Matte = true;
            $scope.cancle_but = true;
            $state.go('rewrite_label',{'id':$stateParams.id,'name':$stateParams.id});  
        }   
    };

    // 删除标签
    if ('pad' == platform) {
        $scope.removeFun = function(){
            var itemId = $stateParams.id;
            if ( itemId == 2 || itemId == 1) {
                alert('无法删除！');
            }else{
                 alert('确认删除！');
                 removeLabel(itemId,$scope,$compile);
                 $scope.Track_Matte = false;
                 $scope.cancle_but = false; 
                 $state.go('menu.label.label_details',{'id':'','name':''});
            };
        } 
    }else{
        $scope.removeFun = function(){
            var itemId = $stateParams.id;
            if ( itemId == 2 || itemId == 1) {
                alert('无法删除');
            }else{
                 removeLabel(itemId,$scope,$compile);
                 $scope.cancle_but = false; 
                 $state.go('label_list',{'id':'','name':''});
            };
        }  
    };
  
    //添加标签成员
    if ('pad' == platform) {
        $scope.AddLabelClientFun = function(selectedRow){
            $scope.title = selectedRow;
            $scope.Track_Matte = true;
            $scope.cancle_but = true;
            $state.go('menu.label.add_label_client',{'id':selectedRow});
        }    
    }else{
       $scope.AddLabelClientFun = function(selectedRow){
            $scope.title = selectedRow;
            $scope.Track_Matte = true;
            $scope.cancle_but = true;
            $state.go('add_label_client',{'id':selectedRow});
        } 
    };
})
//标签详情列表
.controller('LabelCustomerCtrl',function($scope,$state,$rootScope,$compile,$timeout){ 

    //加载客户列表
    $timeout(function(){ 
        customerLabelList("customer",$scope,$compile);
    },500)

    //关闭
    $scope.CloseFun = function(){
        $scope.Track_Matte = false;
        $rootScope.$viewHistory.backView.go();
    }   

    //添加标签成员
    if ('pad' == platform) {
        $scope.AddLabelClientFun = function(selectedRow){
            $scope.title = selectedRow;
            $scope.Track_Matte = true;
            $scope.cancle_but = true;
            $state.go('menu.label.add_label_client',{'id':selectedRow});
        }  
    }else{
       $scope.AddLabelClientFun = function(selectedRow){
           $scope.title = selectedRow;
           $scope.Track_Matte = true;
           $scope.cancle_but = true;
           $state.go('menu.label.add_label_client',{'id':selectedRow});
       }   
    };
    
    //确认添加成员
    if ('pad' == platform) {
        $scope.LaCusSuccessFun = function(selectedRow){
           $scope.Track_Matte = false;
           $state.go('menu.label.add_label',{'id':selectedRow}); 
        } 
    }else{
       $scope.LaCusSuccessFun = function(selectedRow){
          $scope.Track_Matte = false;
          $state.go('add_label',{'id':selectedRow}); 
       }  
    }


/***********************************************js效果***************************************************************/
 
    //全选/取消checkbox
    var num = 0;
    $('.check_all i.circle').on('click',function(){
        if($('.clients_lists a').find('i').hasClass('checked')){
            $(this).removeClass('checked');
            $('.check_all span').text("全选");
            $('.add_label_client .item i.circle').removeClass('checked');
            $('.check_head').text('您还未选择客户');
            $("#new_label .title + .buttons button").css('color','#ccc');
             num = 0;
        }else{
            $(this).addClass('checked');
            $('.check_all span').text("取消");
            $('.add_label_client .item i.circle').addClass('checked');
            num = $('.add_label_client .item i.circle').length;
            $('.check_head').text('已选'+num+'位客户');
            $("#new_label .title + .buttons button").css('color','#fff');
        }
    })

    //单个选取checkbox
    $scope.addlabel = function(i){
        if($('#customer a').eq(i).find('i').hasClass('checked')){
            $('#customer a').eq(i).find('i').removeClass('checked');
            num--;
        }else{
            $('#customer a').eq(i).find('i').addClass('checked');
            num++;
        }
        if(num == 0){
            $('.check_head').text('您还未选择客户');
        }else{
            if(num == $('.add_label_client .item i.circle').length) {
              $('.check_all i.circle').addClass('checked');
            $('.check_all span').text("取消");  
            }
                $('.check_head').text('已选'+num+'位客户');
            
        } 
    } 

    //移除客户
    $('.btn_remove').click(function(){
        $('.clients_lists .item-avatar .left_margin > img:first-child').addClass('remove');
        $('.add_label .added_client .item .left_margin').addClass('remove');
        $('i.remove').show();
    })
    $scope.RemoveFun = function(i){
        $('.add_label .added_client .item').eq(i).remove();
         if($('.add_label .added_client .item').length == 0) {
            $scope.cancle_but = false;
         }else{
            $scope.cancle_but = true;
         }
    }  
})

